package com.gjy.core;

import com.gjy.Level;
import com.gjy.Logger;
import com.gjy.use.File;
import com.gjy.util.StringUtil;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author 宫静雨
 * @version 1.0
 */
public class FileLogger implements Logger {
    private Class<?> clazz;
    public static final File FILE = new File();

    public FileLogger(Class<?> clazz) {
        this.clazz = clazz;
    }

    private void insert(String message, Level level, Throwable... t) {
        try {
            FileWriter fw = FILE.get();
            String standard = StringUtil.standardFile(clazz, message, level);
            if (t.length > 0) {
                standard = standard + "  " + t[0].getMessage();
            }
            fw.write(standard);
            fw.write("\n");
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void info(String message) {
        insert(message, Level.INFO);
    }

    @Override
    public void info(String format, Object... arg) {
        StringBuilder sb = new StringBuilder(format);
        for (Object o : arg) {
            sb.replace(sb.indexOf("{"), sb.indexOf("}") + 1, o.toString());
        }
        insert(sb.toString(), Level.INFO);
    }

    @Override
    public void info(String message, Throwable t) {
        insert(message, Level.INFO, t);
    }

    @Override
    public void debug(String message) {
        insert(message, Level.DEBUG);
    }

    @Override
    public void debug(String format, Object... arg) {
        StringBuilder sb = new StringBuilder(format);
        for (Object o : arg) {
            sb.replace(sb.indexOf("{"), sb.indexOf("}") + 1, o.toString());
        }
        insert(sb.toString(), Level.DEBUG);
    }

    @Override
    public void debug(String message, Throwable t) {
        insert(message, Level.DEBUG, t);
    }

    @Override
    public void warn(String message) {
        insert(message, Level.WARN);
    }

    @Override
    public void warn(String format, Object... arg) {
        StringBuilder sb = new StringBuilder(format);
        for (Object o : arg) {
            sb.replace(sb.indexOf("{"), sb.indexOf("}") + 1, o.toString());
        }
        insert(sb.toString(), Level.WARN);
    }

    @Override
    public void warn(String message, Throwable t) {
        insert(message, Level.WARN, t);
    }

    @Override
    public void error(String message) {
        insert(message, Level.ERROR);
    }

    @Override
    public void error(String format, Object... arg) {
        StringBuilder sb = new StringBuilder(format);
        for (Object o : arg) {
            sb.replace(sb.indexOf("{"), sb.indexOf("}") + 1, o.toString());
        }
        insert(sb.toString(), Level.ERROR);
    }

    @Override
    public void error(String message, Throwable t) {
        insert(message, Level.ERROR, t);
    }
}
